setwd("/scratch/jc227089/evostochData/")

load(file="concat_evostoch_varLam.RData")
no.all<-as.data.frame(concat)
rm(concat, poplist)
load(file="concat_evostoch_Allee.RData")
allee<-as.data.frame(concat)
rm(concat, poplist)

c.df<-no.all
var.summ<-c()
for (ii in 1:nlevels(as.factor(c.df$R0))){
	c.tmp<-subset(c.df, as.numeric(as.factor(c.df$R0))==ii)
	c.no.evol<-subset(c.tmp, c.tmp$evol==0)
	c.evol<-subset(c.tmp, c.tmp$evol==1)
	
	dem.st<-summary(aov(abs.xlim~1, data=c.no.evol))[[1]]$'Sum Sq' #pure demographic stochasticity
	evol.st<-summary(aov(abs.xlim~Error(pop), data=c.evol)) # partitioned into within and between pop (between=founder, within = evol+demographic stoch)
	evol.st.win<-evol.st$'Error: Within'[[1]]$'Sum Sq' #evol+dem st
	evol.st.bw<-evol.st$'Error: pop'[[1]]$'Sum Sq' #initial founder event

	var.summ<-rbind(var.summ, c(R0=as.numeric(levels(as.factor(c.df$R0)))[ii], round(c(demog=dem.st, founder=evol.st.bw, evoln=evol.st.win-dem.st)*100, 2)))
}

c.df<-allee
var.summ.all<-c()
for (ii in 1:nlevels(as.factor(c.df$R0))){
	c.tmp<-subset(c.df, as.numeric(as.factor(c.df$R0))==ii)
	c.no.evol<-subset(c.tmp, c.tmp$evol==0)
	c.evol<-subset(c.tmp, c.tmp$evol==1)
	
	dem.st<-summary(aov(abs.xlim~1, data=c.no.evol))[[1]]$'Sum Sq' #pure demographic stochasticity
	evol.st<-summary(aov(abs.xlim~Error(pop), data=c.evol)) # partitioned into within and between pop (between=founder, within = evol+demographic stoch)
	evol.st.win<-evol.st$'Error: Within'[[1]]$'Sum Sq' #evol+dem st
	evol.st.bw<-evol.st$'Error: pop'[[1]]$'Sum Sq' #initial founder event

	var.summ.all<-rbind(var.summ.all, c(R0=as.numeric(levels(as.factor(c.df$R0)))[ii], round(c(demog=dem.st, founder=evol.st.bw, evoln=evol.st.win-dem.st)*100, 2)))
}

var.summ.all<-rbind(c(2, rep(NA, 3)), var.summ.all)

tot<-apply(var.summ[,2:4], 1, sum)
tot.all<-apply(var.summ.all[,2:4], 1, sum)
prop<-tot.all/tot

pdf('Figures/Stoch_comp.pdf', paper='a4')
	par(mar=c(5,5,1,1), cex.lab=1.4)
	plot(var.summ.all[,1], prop, type="l", bty="l", lwd=3,
		xlab=quote(R[max]), ylab="Proportion of total variance relative to non-Allee model")
dev.off()